package com.example.springboot_practice.Controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: SpringBoot整合Web开发(单文件上传)
 * @Author 王宝凯
 * @Date 2020/9/8
 */
@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest req){
        String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        System.out.println(oldName+"oldName11111");
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
        System.out.println(newName+"newName2222222");
        try {
            uploadFile.transferTo(new File(folder,newName));
            String filePath = req.getScheme() + "://" + req.getServerName() + ":" +req.getServerPort() + "/uploadFile" + format + newName;
            System.out.println(filePath+"22222222222");
            return filePath;
        }catch (IOException e){
            e.printStackTrace();
        }
        return "上传失败！";
    }

    @PostMapping("/uploads")
    public String uploads(MultipartFile[] uploadFiles,HttpServletRequest req){
        List<String> list = new ArrayList<>();
         for (MultipartFile uploadFile : uploadFiles) {
            System.out.println("11111111111111111");
             list.add(upload(uploadFile,req));
        }
        return list.toString();
    }
}
